package databases;


import java.util.ArrayList;

import negocio.Categoria;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DsCategoria {
	private SQLiteDatabase db;
	private Db banco;
	private String tableName = "Categoria";
	private String[] columns = {"_id", "nome"};
	
	public DsCategoria(Context context)
	{
		banco = new Db(context);
	}
	
	public void open() throws SQLException
	{
		db = banco.getWritableDatabase();
	}
	
	public void close()
	{
		db.close();
	}
	
	public boolean isEmpty()
	{
		Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
		
		if(cursor.getCount() == 0)
		{
			cursor.close();
			return true;
		}
		else
		{
			cursor.close();
			return false;
		}
	}

	public Categoria add(String n)
	{
		ContentValues values = new ContentValues();
		values.put("nome", n);
		long insertId = db.insert(tableName, null, values);
		
		if(insertId == -1)
		{
			return null;
		}
		
		Cursor cursor = db.query(tableName, columns, "_id=" + insertId, null, null, null, null);
		cursor.moveToFirst();
		Categoria newCategoria = fromCursor(cursor);
		cursor.close();
		
		return newCategoria;
	}
	
	public boolean rename(long id, String newName)
	{
		ContentValues values = new ContentValues();
		values.put("nome", newName);
		
		if(db.update(tableName, values, "_id=" + id, null) > 0)
		{
			return true;
		}
		
		return false;
	}
	
	public void remove(long id)
	{
		db.delete(tableName, "_id=" + id, null);
	}
	
	public ArrayList<Categoria> getAll()
	{
		ArrayList<Categoria> categorias = new ArrayList<Categoria>();
		
		Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
		
		cursor.moveToFirst();
		while(!cursor.isAfterLast())
		{
			categorias.add(fromCursor(cursor));
			cursor.moveToNext();
		}
		
		cursor.close();
		return categorias;
	}
	
	public boolean hasCategoria(String n){
		Cursor cursor = db.query("Categoria", columns, "nome = '" + n + "'", null, null, null, null);
		
		if(cursor.getCount() > 0)
		{
			cursor.close();
			return true;
		}
		else
		{
			cursor.close();
			return false;
		}
	}
	
	private Categoria fromCursor(Cursor cursor)
	{
		return new Categoria(cursor.getLong(0), cursor.getString(1));
	}
}
